package me.shurufa.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.activities.CommentDetailActivity;
import me.shurufa.activities.NewLoginActivity;
import me.shurufa.activities.NewUserCenterActivity;
import me.shurufa.activities.PhotoViewManager;
import me.shurufa.activities.ShareEditActivity;
import me.shurufa.bean.Excerpt;
import me.shurufa.bean.UserInfoEntity;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.holder.BaseViewHolder;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Utils;

/**
 * 作者 : andy
 * 日期 : 16/3/8 14:50
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 书摘列表适配器
 */
public class BookExcerptAdapter extends RecyclerView.Adapter<BookExcerptAdapter.DigestHolder> {

    private Context mContext;
    private List<Excerpt> mDataList;
    private OnOperateClickListener mOnSocialBarClickListener;

    private int mWhereFrom;
    private String mBookname;

    private SparseBooleanArray mNoteExpandState = new SparseBooleanArray();    // 笔记展开的状态  默认false
    private SparseBooleanArray mCommentExpandState = new SparseBooleanArray(); // 评论展开的状态  默认false

    public BookExcerptAdapter(Context context, String bookname, List<Excerpt> datas, int mWhereFrom) {
        mContext = context;
        this.mDataList = datas;
        this.mWhereFrom = mWhereFrom;
        this.mBookname = bookname;
    }

    @Override
    public DigestHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (Constants.DIGEST_TYPE_IMAGE == viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_bookdetail_digest_type_img, parent, false);
            return new DigestHolder(v);
        }

        if (Constants.DIGEST_TYPE_TEXT == viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_bookdetail_digest, parent, false);
            return new DigestHolder(v);
        }

        // default
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_bookdetail_digest, parent, false);
        return new DigestHolder(v);
    }

    @Override
    public int getItemViewType(int position) {
        Excerpt digest = mDataList.get(position);
        return digest.type;
    }

    @Override
    public int getItemCount() {
        return mDataList.size();
    }

    @Override
    public void onBindViewHolder(final DigestHolder holder, final int position) {
        try {
            bindData(holder, position);
            bindListener(holder, position);
        } catch (Exception e) {
            e.printStackTrace();
            Utils.showToast(R.string.sys_err);
        }
    }

    private void bindData(DigestHolder holder, int position) {
        // 书摘
        Excerpt excerpt = mDataList.get(position);

        if (Constants.DIGEST_TYPE_TEXT == excerpt.type) {
            holder.iv_digest_content.setVisibility(View.GONE);
            holder.tv_digest_content.setVisibility(View.VISIBLE);
            holder.tv_digest_content.setText(excerpt.content);
        } else {
            holder.iv_digest_content.setVisibility(View.VISIBLE);
            holder.tv_digest_content.setVisibility(View.GONE);
            // 图片书摘
            Glide.with(mContext)
                    .load(excerpt.screenshot + Constants.THUMB_SUFFIX)
                    .centerCrop()
                    .placeholder(R.drawable.ic_placeholder_digest_image)
                    .error(R.drawable.ic_placeholder_digest_image)
                    .into(holder.iv_digest_content);
        }

        // 用户
        UserInfoEntity user_info = excerpt.user_info;
        if (null != user_info) {
            holder.tv_mark_user.setText(user_info.username);
        }

        // 笔记
        holder.tv_chapter.setText(mContext.getString(R.string.chapter_suffix) + excerpt.menu_title);
        holder.tv_chapter.setVisibility(TextUtils.isEmpty(excerpt.menu_title) ? View.INVISIBLE : View.VISIBLE);
        holder.tv_mark_content.setText(excerpt.note);
        holder.tv_note_create_time.setText(Utils.getFormatTime(String.valueOf(excerpt.updated_at)));

        // 若无笔记内容，则显示暂无笔记
        boolean hasNote = !TextUtils.isEmpty(excerpt.note);
        holder.tv_mark_content.setVisibility(hasNote ? View.VISIBLE : View.GONE);
        holder.tv_no_note.setVisibility(hasNote ? View.GONE : View.VISIBLE);

        // 页数
        holder.tv_page_no.setText("P."+excerpt.page_num);
        holder.tv_page_no.setVisibility(excerpt.page_num == 0 ? View.INVISIBLE : View.VISIBLE);

        // 四个操作按钮
        boolean isZero = excerpt.zan_num == 0;
        holder.tv_praise_num.setText(isZero ? null : String.valueOf(excerpt.zan_num));
        holder.tv_comment_num.setText(excerpt.comment_num == 0 ? null : String.valueOf(excerpt.comment_num));

        holder.tv_praise.setBackgroundResource(excerpt.is_zan != 0 ? R.drawable.ic_praise_selected : R.drawable.ic_praise_normal);
        holder.tv_collect.setBackgroundResource(excerpt.is_fav != 0 ? R.drawable.ic_collect_selected : R.drawable.ic_collect_normal);

        // 若是从消息中心跳进来的，不显示四个操作按钮，并且默认展开评论列表且不可收起
        if (Constants.TYPE_FROM_NOTICE_MESSAGE_DIGEST == mWhereFrom) {
            // 不显示四个操作按钮
            holder.layout_social_bar.setVisibility(View.GONE);
            // 默认展开评论列表
            mCommentExpandState.put(position, true);
            holder.ll_collapse.setVisibility(View.GONE);
        }

        //bindCommentData(holder, position);

        boolean isNoteExpand = mNoteExpandState.get(position);
        holder.expand_view.setImageResource(isNoteExpand ? R.drawable.ic_arrow_top : R.drawable.ic_arrow_bottom);
        holder.layout_mark_content.setVisibility(mNoteExpandState.get(position) ? View.VISIBLE : View.GONE);
        //holder.expand_comment_layout.setVisibility(mCommentExpandState.get(position) ? View.VISIBLE : View.GONE);
    }


    private void bindListener(final DigestHolder holder, final int position) {

        final Excerpt excerpt = mDataList.get(position);
        // 昵称点击 进入用户详情界面
        if (Constants.FROM_USER_CENTER != mWhereFrom) {
            holder.tv_mark_user.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent in = new Intent(mContext, NewUserCenterActivity.class);
                    NewUserCenterActivity.initArguments(in, excerpt.user_info, true);
                    mContext.startActivity(in);
                }
            });
        }

        // 进入到分享界面
        holder.btn_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent in = new Intent(mContext, ShareEditActivity.class);
                ShareEditActivity.initArguments(in, mBookname, excerpt, null);
                mContext.startActivity(in);
            }
        });

        // 点击图片书摘 查看大图
        holder.iv_digest_content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PhotoViewManager.loadImage(mContext, excerpt.screenshot);
            }
        });
        holder.btn_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent in = new Intent(mContext, CommentDetailActivity.class);
                CommentDetailActivity.initArguments(in, mBookname, excerpt.id, Constants.TYPE_COMMENT_EXCERPT);
                mContext.startActivity(in);
            }
        });


        // 点击箭头展开/收回笔记
        holder.expand_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isNoteExpand = mNoteExpandState.get(position);
                holder.layout_mark_content.setVisibility(isNoteExpand ? View.GONE : View.VISIBLE);
                holder.expand_view.setImageResource(!isNoteExpand ? R.drawable.ic_arrow_top : R.drawable.ic_arrow_bottom);
                mNoteExpandState.put(position, !isNoteExpand);
            }
        });


        // 点击点赞
        holder.btn_praise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!handleLoginClick()) {
                    return;
                }
                if (null != mOnSocialBarClickListener) {
                    mOnSocialBarClickListener.onPraiseClick(excerpt.is_zan != 0, excerpt);
                }
            }
        });

        // 点击收藏
        holder.btn_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!handleLoginClick()) {
                    return;
                }
                if (null != mOnSocialBarClickListener) {
                    mOnSocialBarClickListener.onCollectClick(excerpt.is_fav != 0, excerpt);
                }
            }
        });
    }

    public class DigestHolder extends BaseViewHolder {
        @Bind(R.id.social_bar_layout)
        LinearLayout layout_social_bar;  // 操作按钮

        @Bind(R.id.tv_digest_content)
        TextView tv_digest_content;
        @Bind(R.id.iv_digest_content)
        ImageView iv_digest_content;
        @Bind(R.id.tv_mark_user)
        TextView tv_mark_user;
        @Bind(R.id.tv_mark_content)
        TextView tv_mark_content;

        @Bind(R.id.ll_praise)
        LinearLayout btn_praise;
        @Bind(R.id.ll_collect)
        LinearLayout btn_collect;
        @Bind(R.id.tv_praise_num)
        TextView tv_praise_num;
        @Bind(R.id.tv_comment_num)
        TextView tv_comment_num;

        @Bind(R.id.tv_praise)
        TextView tv_praise;
        @Bind(R.id.tv_collect)
        TextView tv_collect;

        @Bind(R.id.ll_share)
        LinearLayout btn_share;
        @Bind(R.id.ll_comment)
        LinearLayout btn_comment;

        @Bind(R.id.expand_view)
        ImageView expand_view;
        @Bind(R.id.ll_collapse)
        LinearLayout ll_collapse;

        @Bind(R.id.layout_mark_content)
        LinearLayout layout_mark_content;

        @Bind(R.id.tv_chapter)
        TextView tv_chapter;
        @Bind(R.id.tv_page_no)
        TextView tv_page_no;
        @Bind(R.id.tv_note_create_time)
        TextView tv_note_create_time;

        @Bind(R.id.tv_no_note)
        TextView tv_no_note;


        public DigestHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

    }

    public void setOnSocialBarClickListener(OnOperateClickListener l) {
        this.mOnSocialBarClickListener = l;
    }

    /**
     * 评论按钮点击接口
     */
    public interface OnOperateClickListener {
        /**
         * 点击点赞按钮
         * @param prePraise
         * @param excerpt     true: 点赞   false: 取消点赞
         */
        void onPraiseClick(boolean prePraise, Excerpt excerpt);

        /**
         * 点击收藏按钮
         * @param preCollect true: 收藏   false: 取消收藏
         * @param excerpt
         */
        void onCollectClick(boolean preCollect, Excerpt excerpt);
    }

    public void append(List<Excerpt> items) {
        if (Utils.isNullForList(items)) {
            return;
        }
        int pos = mDataList.size();
        for (Excerpt item : items) {
            if (!mDataList.contains(item)) {
                mDataList.add(item);
                mNoteExpandState.append(mDataList.size() - 1, false);
                mCommentExpandState.append(mDataList.size() - 1, false);
            }
        }
        notifyItemRangeInserted(pos, items.size());
    }

    public void clear() {
        int size = mDataList.size();
        mDataList.clear();
        mNoteExpandState.clear();
        mCommentExpandState.clear();
        this.notifyItemRangeRemoved(0, size);
    }

    private boolean handleLoginClick() {
        boolean isLogin = PersistenceUtils.isLogin();
        Intent in = null;
        // 已登录 跳转到ProfileActivity
        if (isLogin) {
            return true;
        }

        // 未登录 则跳转至登录界面，点击登录时需要返回到当前界面
        else {
            in = new Intent(mContext, NewLoginActivity.class);
            in.setAction(Constants.ACTION_GO_LOGIN);
            EventBus.getDefault().postSticky(in);
            return false;
        }
    }

}
